package com.shop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.shop.bean.Goods;
import com.shop.dao.BaseDao;
import com.shop.dao.GoodsDao;

public class GoodsDaoImpl implements GoodsDao {

	@Override
	public List<Goods> selectAllGoods(int pageNum,int pageSize) {
		List<Goods> goodsList = new ArrayList();
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		String sql = "SELECT * FROM goods LIMIT ?,?";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, (pageNum-1)*pageSize);
			ps.setInt(2, pageSize);
			res = ps.executeQuery();
			while(res.next()) {
				Goods goods = new Goods();
				goods.setGoodsId(res.getInt("goodsId"));
				goods.setGoodsName(res.getString("goodsName"));
				goods.setGoodsFactory(res.getString("goodsFactory"));
				goods.setGoodsNum(res.getInt("goodsNum"));
				goods.setGoodsType(res.getString("goodsType"));
				goods.setGoodsPrice(res.getDouble("goodsPrice"));
				goodsList.add(goods);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(res, ps, con);
		}
		return goodsList;
	}

	@Override
	public int selectAllGoodsNum() {
		int rows = 0;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		String sql = "SELECT count(1) as rows FROM goods";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			res = ps.executeQuery();
			if(res.next()) {
				rows = res.getInt("rows");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(res, ps, con);
		}
		return rows;
	}

}
